﻿using System;
using System.Collections.Generic;
using System.Text;
using DoxygenBrowser.Common.InOut;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace GenTDictionaryFile
{
  class Program
  {
    private const string CONST_OUT_FILE = "tokens.tdic";

    private const int OPT_ANALYZE = 0;
    private const int OPT_GEN_TDIC = 1;


    static void Main(string[] args)
    {
      try
      {
        int iOption = OPT_GEN_TDIC;

        // process arguments
        int iArg = 0;
        bool bProcessed = false;
        while((iArg < args.Length) && !bProcessed)
        {
          string strOption = args[iArg].ToLower();
          switch(strOption)
          {
            case "-a":
              iOption = OPT_ANALYZE;
              iArg++;
              break;
            default:
              bProcessed = true;
              break;
          }

        }

        if (iArg >= args.Length)
        {
          showHelp();
        }
        else
        {
          string strTokensPath = args[iArg];
          switch (iOption)
          {
            case OPT_ANALYZE:
              AnalyzeFile(strTokensPath);
              break;
            case OPT_GEN_TDIC:
              GenTDictionary(strTokensPath);
              break;
          }
        }
      }
      catch(Exception ex)
      {
        Console.Write(ex.Message);
      }

    }

    private static void GenTDictionary(string strTokensPath)
    {
      TDictionaryFileWriter tDictionaryFileWriter = new TDictionaryFileWriter(strTokensPath);
      if (tDictionaryFileWriter.ProcessTokensFile())
      {
        TDictionaryFile tDictionary = tDictionaryFileWriter.TDictionaryFile;
        saveTDictionary(tDictionary, CONST_OUT_FILE);
      }

    }


    private static void AnalyzeFile(string strTokensPath)
    {
      {
        TDictionaryAnalyser tDictionaryAnalyzer = new TDictionaryAnalyser(strTokensPath);
        if (tDictionaryAnalyzer.ProcessTokensFile())
        {
          StringBuilder sb = new StringBuilder();
          tDictionaryAnalyzer.WriteResult(sb);
          Console.Write(sb.ToString());
        }
      }
    }

    private static void saveTDictionary(TDictionaryFile tDictionary, string strPath)
    {
      using (Stream stream = File.Open(strPath, FileMode.Create))
      {
        BinaryFormatter bformatter = new BinaryFormatter();
        bformatter.Serialize(stream, tDictionary);
        stream.Close();
      }
    }

    private static void showHelp()
    {
      Console.WriteLine("Usage: {0} 'tokens.xml'", "GenTDictionaryFile");
    }
  }
}
